package cus179.config;

import cn.hutool.extra.spring.SpringUtil;
import cus179.constant.UKeyMethod;
import cus179.dto.SignRequest;
import cus179.dto.WebSocketWrapper;
import cus179.handler.WebSocketClientHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 周鑫
 * @version 1.0.0
 * @Description 初始化配置
 * @createTime 2024年02月22日 10:17
 */
@Slf4j
@Configuration
public class InitConfig {

    /**
     * jackson序列化处禁止换成其他json序列化工具
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * ukey默认密码8个8不要修改
     */
    private static final String DEFAULT_PASSWORD = "88888888";


    /**
     * 取海关签名证书PEM, X509Certificate证书（未经HASH算法散列过）
     *
     * @return 取海关签名证书PEM, X509Certificate证书是加签证书，真正的X509Certificate证书
     */
    @SneakyThrows
    public static String getX509CertificateParameter() {
        Map<String, Object> parameterMap = new LinkedHashMap<>(3);
        parameterMap.put("_method", UKeyMethod.SIGN_CERT_AS_PEM);
        parameterMap.put("_id", 1);
        parameterMap.put("args", "{}");
        return MAPPER.writeValueAsString(parameterMap);
    }

    /**
     * 签名, 不对原文计算摘要, 请您自行计算好摘要传入
     *
     * @param request 原文入参
     * @return SignatureValue的值, 返回的数组，包含您的证书编号，可作为KeyName的值
     */
    @SneakyThrows
    public static String getSignDataAsPEMParameter(SignRequest request) {
        Map<String, Object> args = new LinkedHashMap<>(2);
        args.put("inData", request.getData());
        args.put("passwd", ObjectUtils.defaultIfNull(SpringUtil.getBean(UkeyProperties.class).getPassword(), DEFAULT_PASSWORD));
        Map<String, Object> parameterMap = new LinkedHashMap<>(3);
        parameterMap.put("_method", UKeyMethod.SIGN_DATA_AS_PEM);
        parameterMap.put("_id", request.getId());
        parameterMap.put("args", args);
        return MAPPER.writeValueAsString(parameterMap);
    }

    @Bean
    @ConditionalOnMissingBean({StandardWebSocketClient.class})
    public StandardWebSocketClient standardWebSocketClient() {
        return new StandardWebSocketClient();
    }

    @Bean
    public WebSocketWrapper webSocketWrapper() {
        return new WebSocketWrapper();
    }

    @Bean
    @ConditionalOnMissingBean({WebSocketClientHandler.class})
    public WebSocketClientHandler webSocketClientHandler(UkeyProperties ukeyProperties, WebSocketWrapper webSocketWrapper) {
        return new WebSocketClientHandler(ukeyProperties, webSocketWrapper);
    }

}
